"use client";

import { useForm, FieldValues, SubmitHandler } from 'react-hook-form'
import { useState } from 'react';
import toast from 'react-hot-toast';
import uniqid from 'uniqid';
import { useSupabaseClient } from '@supabase/auth-helpers-react';
import { useRouter } from 'next/navigation';

import Modal from "./Modal";
import Input from './Input';
import Button from './Button';
import useUploadModal from "@/hooks/useUploadModal";
import { useUser } from '@/hooks/useUser';

const UploadModal = () => {
  const uploadModal = useUploadModal();
  const { user } = useUser();
  const [isLoading, setIsLoading] = useState(false); 
  const supabaseClient = useSupabaseClient();
  const router = useRouter();

  const {
    register,
    handleSubmit,
    reset
  } = useForm<FieldValues>({
    defaultValues: {
      author: '',
      title: '',
      song: null,
      image: null
    }
  });

  const onChange = (open: boolean) => {
    if(!open){
      //表单会安全的重置
      reset();
      uploadModal.onClose();
    }
  }

  const onSubmit: SubmitHandler<FieldValues> = async(values) => {
    try{
      setIsLoading(true);

      /**
       console.log(values);
       * {
            "author": "Antonio",
            "title": "All of me",
            "song": {0: File, length: 1},
            "image": {0: File, length: 1}
        }
       */

      //获取文件
      const imageFile = values.image?.[0];
      const songFile = values.song?.[0];
      
      if(!imageFile || !songFile || !user){
        toast.error('丢失了某个字段信息。');
        return;
      }
      
      //上传歌曲文件至supabase数据库
      const uniqueID = uniqid();
      const {
        data: songData,
        error: songError
      } = await supabaseClient
        .storage
        .from('songs')
        .upload(
          `song-${values.title}-${uniqueID}`,
          songFile,
          {
            cacheControl: '3600',
            upsert: false
          }
        );

      if(songError){
        setIsLoading(false);
        return toast.error('歌曲文件上传失败。');
      }

      //上传歌曲图片至supabase数据库
      const {
        data: imageData,
        error: imageError
      } = await supabaseClient
        .storage
        .from('images')
        .upload(
          `image-${values.title}-${uniqueID}`,
          imageFile,
          {
            cacheControl: '3600',
            upsert: false
          }
        );

      if(imageError){
        setIsLoading(false);
        return toast.error('歌曲图片上传失败。');
      }

      const { error: supabaseError } = await supabaseClient
        .from('songs')
        .insert({
          user_id: user.id,
          title: values.title,
          author: values.author,
          image_path: imageData.path,
          song_path: songData.path
        });
      
      if(supabaseError){
        setIsLoading(false);
        return toast.error(supabaseError.message);
      }
      
      router.refresh();
      setIsLoading(false);
      toast.success('歌曲上传成功！');
      reset();
      uploadModal.onClose();

    }catch(e){
      toast.error("Ohpps.....哪里出错了。");
    }finally{
      setIsLoading(false);
    }

  }

  return (
    <Modal
      title = "添加歌曲"
      description="请上传mp3文件"
      isOpen={uploadModal.isOpen}
      onChange={onChange}
    >
      <form
        onSubmit={handleSubmit(onSubmit)}
        className="
          flex
          flex-col
          gap-y-4
        "
      >
        <Input
          id="title"
          disabled={isLoading}
          {...register('title', { required: true })}
          placeholder="歌曲名称"
        />
        <Input
          id="author"
          disabled={isLoading}
          {...register('author', { required: true })}
          placeholder="歌曲作者"
        />
        <div>
          <div className="pb-1">请选择歌曲文件</div>
          <Input
            id="song"
            type="file"
            accept=".mp3"
            disabled={isLoading}
            {...register('song', { required: true })}
          />    
        </div>
        <div>
          <div className="pb-1">请选择歌曲图片</div>
          <Input
            id="image"
            type="file"
            accept="image/*"
            disabled={isLoading}
            {...register('image', { required: true })}
          />    
        </div>
        <Button
          disabled={isLoading}
          type="submit"
        >添加</Button>
      </form>
    </Modal>
  )
}

export default UploadModal